package com.ivo.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ListMap<K, T>
{
	protected ArrayList<K> keys;
	protected HashMap<K, T> items;

	public ListMap()
	{
		keys = new ArrayList<K>();
		items = new HashMap<K, T>();
	}

	public ListMap(int capacity)
	{
		keys = new ArrayList<K>( capacity );
		items = new HashMap<K, T>( capacity );
	}

	public void clear()
	{
		keys.clear();
		items.clear();
	}

	public int indexOf(K key)
	{
		return keys.indexOf( key );
	}

	public T get(int index)
	{
		K key = keys.get( index );
		return items.get( key );
	}

	public T get(K key)
	{
		return items.get( key );
	}

	public List<K> getKeys()
	{
		return keys;
	}

	public int size()
	{
		return keys.size();
	}

	public boolean containsKey(K key)
	{
		return keys.contains( key );
	}

	public void add(K key, T item)
	{
		if( !keys.contains( key ) ) keys.add( key );
		items.put( key, item );
	}

	public void add(int index, K key, T item)
	{
		if( keys.contains( key ) ) keys.remove( key );
		keys.add( index, key );
		items.put( key, item );
	}

	public void set(int index, K key, T item)
	{
		keys.set( index, key );
		items.put( key, item );
	}

	public T remove(int index)
	{
		if( keys.size() <= 0 ) return null;
		K key = keys.get( index );

		return remove( key );
	}

	public T remove(K key)
	{
		keys.remove( key );
		return items.remove( key );
	}

	public String toString()
	{
		StringBuilder str_buf = new StringBuilder();
		//-------------------------------------------------------------------------------------------------------------------------------------
		str_buf.append( "COUNT(" );
		str_buf.append( size() );
		str_buf.append( ") { " );
		//-------------------------------------------------------------------------------------------------------------------------------------
		for( int i = 0; i < size(); i++ ) {
			if( i > 0 ) str_buf.append( ", " );
			K key = keys.get( i );
			T item = get( key );
			//-------------------------------------------------------------------------------------------------------------------------------------
			if( key != null ) str_buf.append( key.toString() );
			str_buf.append( "=" );
			if( item != null ) str_buf.append( item.toString() );

		} // for i
		str_buf.append( "; } " );

		return str_buf.toString();
	}
}
